<?php
    class iJBlock implements iJSingleton{
        private $tockens;
        /**
         *
         * This function is Block construct
         *
         * @access public
         */
        public function __construct() {
        }
        
        /**
         * Executes the block to generate the tokens
         *
         * @return array Array with the tokens of the block
         *
         * @access public
         */
        public function execute()
        {
            return $this->tockens;
        }
        
        /**
         *
         * Executes the block to generate the tokens
         *
         * @return array Array with the tokens of the block
         *
         * @access public
         */
        public function addToken($name, $value)
        {
            $this->tockens[$name] = $value;
            
        }
        
        public function deleteBlock($blockID) {
            $iJLanguages = iJFactory::singleton('iJLanguages');
            $block = self::getBlockInfo($blockID);
            if(empty($block)) {
                iJMessages::display('warning', 'warning', 'block_not_found');
                return;
            }
            $iJLanguages->removeDefinitions(TABLE_BLOCKS, $blockID);
            
            /*removing class*/
            $location = iJFactory::getLocation($block['code']);
            if($location != false) {
                unlink($location);
            }
            
            /*removing taplate*/
            $templates = iJScanDir(DIR_TEMPLATES, true, true, true, false, 'tpl');
            if(file_exists($templates[strtolower($block['template'])])) {
                unlink($templates[strtolower($block['template'])]); 
            }
            
            /*removing languages*/
            $languages = $iJLanguages->getLanguages();
            $block['isAmdin'] = 0;
            if($block['isAdmin'] != 1) {
               $path =  DIR_FRONTEND_LANGUAGES; 
            } else {
               $path =  DIR_BACKEND_LANGUAGES; 
            }
            
            foreach($languages as $lang) {
                $langFiles = iJScanDir($path . $lang['code'] . '/', true, true, true, false, 'xml');
                if(file_exists($langFiles[strtolower($block['language'])])) {
                   unlink($langFiles[strtolower($block['language'])]);  
                }
                
            }
            
            /*removing from BD*/
            $iJDataBase =  iJFactory::singleton('iJDataBase');
            $QBlocks = $iJDataBase->query("DELETE FROM :table_blocks
                                                 WHERE id = :id");
            $QBlocks->bindTable(':table_blocks', TABLE_BLOCKS);
            $QBlocks->bindValue(':id', $blockID, 'int');
            $QBlocks->execute();
            
            
            
            iJMessages::display('success', 'deleted');

        }
        
        public function createBlock($blockInfo) {
          $iJDataBase  =  iJFactory::singleton('iJDataBase');
          $iJLanguages =  iJFactory::singleton('iJLanguages'); 
          /*Data validation*/
          if (!iJValidation::name($blockInfo['template'])){
             iJMessages::display('fail', 'fail', 'incorrect_template_name');
             return;
          }         
           
          if (!iJValidation::name($blockInfo['CSS'], 0)){
             iJMessages::display('fail', 'fail', 'incorrect_CSS_name');
             return;
          }
          if (!iJValidation::name($blockInfo['JS'], 0)){
             iJMessages::display('fail', 'fail', 'incorrect_JS_name');
             return;
          }        
          
          if (!iJValidation::name($blockInfo['class'], 0)){
             iJMessages::display('fail', 'fail', 'incorrect_class');
             return;
          }
          
          if (!iJValidation::name($blockInfo['language'])){
             iJMessages::display('fail', 'fail', 'incorrect_language');
             return;
          }
          
          if (!iJValidation::Unex_symb($blockInfo['description'], 0)){
             iJMessages::display('fail', 'fail', 'incorrect_description');
             return;
          }
         
   
          $iJDataBase->startTransaction();
          $className = $blockInfo['class'];
          if(!empty($className)) {
            if(strtolower(substr($className, -4)) == '.php') {
              $className = substr($className, 0, strlen($className) - 4);
            }
          } else {
            $className = '';
          }
          
          /*Adding file description if not defined*/
          if(strtolower(substr($blockInfo['template'], -4)) != '.tpl') {
            $blockInfo['template'] = $blockInfo['template'] . '.tpl';
          }
          
          if(strtolower(substr($blockInfo['language'], -4)) != '.xml') {
            $blockInfo['language'] = $blockInfo['language'] . '.xml';
          }
          
          if(strtolower(substr($blockInfo['CSS'], -4)) != '.css' && !empty($blockInfo['CSS'])) {
            $blockInfo['CSS'] = $blockInfo['CSS'] . '.css';
          }
          
          if(strtolower(substr($blockInfo['JS'], -3)) != '.js'   && !empty($blockInfo['JS'])) {
            $blockInfo['JS'] = $blockInfo['JS'] . '.js';
          }
          
          $QBlocks = $iJDataBase->query('INSERT INTO :table_blocks 
                                                    (
                                                        code,
                                                        template,
                                                        language,
                                                        css,
                                                        js,
                                                        isAdmin
                                                    )
                                                    VALUES 
                                                    (
                                                        :code,
                                                        :template,
                                                        :language,
                                                        :css,
                                                        :js,
                                                        :isAdmin
                                                        
                                                    )');
          $QBlocks->bindTable(':table_blocks',  TABLE_BLOCKS);
          $QBlocks->bindValue(':code',          $className);
          $QBlocks->bindValue(':template',      $blockInfo['template']);
          $QBlocks->bindValue(':language',      $blockInfo['language']);
          $QBlocks->bindValue(':css',           $blockInfo['CSS']);
          $QBlocks->bindValue(':js',            $blockInfo['JS']);
          $QBlocks->bindValue(':isAdmin',       isset($blockInfo['admin']) ? 1 : 0);
          $QBlocks->execute();
          if(!$iJDataBase->isError()) {
            $id = $iJDataBase->getLastInsertId();
            $languages = $iJLanguages->getLanguages();
            foreach($languages as $lang) {
                if(isset($blockInfo['title_' . $lang['code']]) && !empty($blockInfo['title_' . $lang['code']])) {
                    $definition = $blockInfo['title_' . $lang['code']];
                } else {
                    $definition = $iJLanguages->getTocken('unset');
                }
                $iJLanguages->addDefinition(TABLE_BLOCKS, $id, $lang['code'], $definition);
                
            }
            $warnings  = '';
            if(!$iJDataBase->isError()) {
                if(isset($blockInfo['admin'])) {
                    /*Creating backend block*/
                    if(isset($blockInfo['class'])) {                 
                      $warnings = $warnings . $this->createBlockClass($blockInfo['class'], DIR_BACKEND_CLASSES, $blockInfo['description']);
                    }
                    $warnings = $warnings . $this->createBlockTemplate($blockInfo['template'], DIR_BACKEND_TEMPLATES, $blockInfo['class']);
                    $warnings = $warnings . $this->createBlockLanguge($blockInfo['language'],  DIR_BACKEND_LANGUAGES); 
                } else {
                    /*creating frontend block*/
                    if(isset($blockInfo['class'])) {
                        $warnings = $warnings . $this->createBlockClass($blockInfo['class'],   DIR_FRONTEND_CLASSES, $blockInfo['description']);
                    }
                    
                    $warnings = $warnings . $this->createBlockTemplate($blockInfo['template'], DIR_FRONTEND_TEMPLATES, $blockInfo['class']);
                    $warnings = $warnings . $this->createBlockLanguge($blockInfo['language'],  DIR_FRONTEND_LANGUAGES); 
                }
                
                $iJDataBase->commitTransaction();
                if($warnings == '') {
                  iJMessages::display('success', 'created');
                } else {
                  iJMessages::display('warning', 'files_exists', $warnings);
                }
                
            } else {
                iJMessages::display('fail', 'fail');
                $iJDataBase->rollbackTransaction();
            }
            
          }
          
            
        }
        
        
         public function editBlock($blockInfo) {
          $iJDataBase  =  iJFactory::singleton('iJDataBase');
          $iJLanguages =  iJFactory::singleton('iJLanguages');
          /*Data check*/
         
          if(empty($blockInfo['id'])) {
            iJMessages::display('fail', 'fail');
            return;
          }
          if(empty($blockInfo['template'])) {
            iJMessages::display('fail', 'fail');
            return;
          }
          
          if(empty($blockInfo['language'])) {
            iJMessages::display('fail', 'fail');
            return;
          }
                  
          if (!iJValidation::name($blockInfo['template'])){
             iJMessages::display('fail', 'fail', 'incorrect_template_name');
             return;
          }         
           
          if (!iJValidation::name($blockInfo['CSS'], 0)){
             iJMessages::display('fail', 'fail', 'incorrect_CSS_name');
             return;
          }
          if (!iJValidation::name($blockInfo['JS'], 0)){
             iJMessages::display('fail', 'fail', 'incorrect_JS_name');
             return;
          }        
          
          if (!iJValidation::name($blockInfo['class'], 0)){
             iJMessages::display('fail', 'fail', 'incorrect_class');
             return;
          }
          
          if (!iJValidation::name($blockInfo['language'])){
             iJMessages::display('fail', 'fail', 'incorrect_language');
             return;
          }
          
          if (!iJValidation::Unex_symb($blockInfo['description'], 0)){
             iJMessages::display('fail', 'fail', 'incorrect_description');
             return;
          }
                  
          /*Adding file description if not defined*/
          $className = $blockInfo['class'];
          if(!empty($className)) {
            if(strtolower(substr($className, -4)) == '.php') {
              $className = substr($className, 0, strlen($className) - 4);
            }
          } else {
            $className = '';
          }
          if(strtolower(substr($blockInfo['template'], -4)) != '.tpl') {
            $blockInfo['template'] = $blockInfo['template'] . '.tpl';
          }
          
          if(strtolower(substr($blockInfo['language'], -4)) != '.xml') {
            $blockInfo['language'] = $blockInfo['language'] . '.xml';
          }
          
          if(strtolower(substr($blockInfo['CSS'], -4)) != '.css' && !empty($blockInfo['CSS'])) {
            $blockInfo['CSS'] = $blockInfo['CSS'] . '.css';
          }
          
          if(strtolower(substr($blockInfo['JS'], -3)) != '.js'   && !empty($blockInfo['JS'])) {
            $blockInfo['JS'] = $blockInfo['JS'] . '.js';
          }
          
          $iJDataBase->startTransaction();
          if(isset($blockInfo['rename'])) {
            $oldInfo   = $this->getBlockInfo($blockInfo['id']);
            $classFile = iJFactory::getLocation($oldInfo['code']); 
              
            if($oldInfo['isAdmin']) {
              $phpPath = DIR_BACKEND_CLASSES;
              $tplPath = DIR_BACKEND_TEMPLATES;
              $lanPath = DIR_BACKEND_LANGUAGES;
            } else {
              $phpPath = DIR_FRONTEND_CLASSES;
              $tplPath = DIR_FONTEND_TEMPLATES;
              $lanPath = DIR_FRONTEND_LANGUAGES;
            }
            
            if(!empty($className) && $className!='' && file_exists($classFile)) {
              rename($classFile, $phpPath . $className . '.php');
              $content = file_get_contents($phpPath . $className . '.php', FILE_TEXT);
              $content = str_replace($oldInfo['code'], $className, $content);
              $file = fopen($phpPath . $className . '.php', "w");
              fwrite($file,utf8_encode($content)); 
              fclose ($file);
            }
            
            if(!empty($blockInfo['template']) && $blockInfo['template'] != '' && file_exists($tplPath . $oldInfo['template'])) {
              rename($tplPath . $oldInfo['template'], $tplPath . $blockInfo['template']);
            }
            
            if(!empty($blockInfo['language']) && $blockInfo['language'] != '') {   
              $languages = $iJLanguages->getLanguages();
              foreach($languages as $lang) {
                if(file_exists($lanPath . $lang['code'] . '/' . $oldInfo['language'])) {
                  rename($lanPath . $lang['code'] . '/' . $oldInfo['language'], $lanPath .  $lang['code'] . '/' . $blockInfo['language']);
                }
                
              }
            }
          }
          
          
          $QBlocks = $iJDataBase->query('UPDATE  :table_blocks 
                                        SET code = :code,
                                            template = :template,
                                            language = :language,
                                            css = :css,
                                            js  = :js
                                        WHERE id = :id
                                                    ');
          $QBlocks->bindTable(':table_blocks',  TABLE_BLOCKS);
          $QBlocks->bindValue(':id',            $blockInfo['id']);
          $QBlocks->bindValue(':code',          $blockInfo['class']);
          $QBlocks->bindValue(':template',      $blockInfo['template']);
          $QBlocks->bindValue(':language',      $blockInfo['language']);
          $QBlocks->bindValue(':css',           $blockInfo['CSS']);
          $QBlocks->bindValue(':js',            $blockInfo['JS']);
          $QBlocks->execute();
          //spr($blockInfo);die();
          if(!$iJDataBase->isError()) {
            $iJLanguages->addDefinition(TABLE_BLOCKS, $blockInfo['id'], $iJLanguages->getLangCode(), $blockInfo['title']);

            if(!$iJDataBase->isError()) {
                $iJDataBase->commitTransaction();
                iJMessages::display('success', 'edited');
            } else {
                iJMessages::display('fail', 'fail');
                $iJDataBase->rollbackTransaction();
            }
            
          }
          
            
        }
        
        
        public static function getBlockInfo($blockID) {
            $iJDataBase =  iJFactory::singleton('iJDataBase');
            $QBlocks = $iJDataBase->query("SELECT B.id, 
                                               B.CODE, 
                                               B.template, 
                                               B.LANGUAGE,
                                               B.isAdmin
                                        FROM :table_blocks AS B
                                        WHERE id = :id");
            $QBlocks->bindTable(':table_blocks', TABLE_BLOCKS);
            $QBlocks->bindValue(':id', $blockID, 'int');
            $QBlocks->execute();
            $block = array();
            
            if($QBlocks->next()) {
                $block['code'] =  $QBlocks->value('CODE');
                $block['language'] =  $QBlocks->value('LANGUAGE');
                $block['template'] =  $QBlocks->value('template');
                $block['isAdmin'] =  $QBlocks->value('isAdmin');
                $block['id'] =  $QBlocks->value('id');                  
            }
            
            return $block;
        }
        
        public function getBlocksList($page, $search, $groupId, $limit = '') {
          $iJDataBase =  iJFactory::singleton('iJDataBase');
          $iJGroups   =  iJFactory::singleton('iJGroups');
          
          $QBlocks = $iJDataBase->query('SELECT B.id, 
                                               def.value as title,
                                               B.CODE, 
                                               B.template, 
                                               B.LANGUAGE,
                                               B.css, 
                                               B.js 
                                        FROM :table_blocks AS B
                                              LEFT JOIN :table_groups AS g ON B.isAdmin = g.id
                                             :lang_join');
          $QBlocks->bindTable(':table_blocks', TABLE_BLOCKS);
          $QBlocks->bindTable(':table_groups', TABLE_GROUPS);
          $QBlocks->bindLaguageDefinitions(':lang_join', TABLE_BLOCKS, 'B');
          
          if(!empty($search)) {
            $QBlocks->appendQuery('AND def.value like :search');
            $QBlocks->bindValue(':search', '%' . $search . '%');
          }
          if($groupId != $iJGroups->getAllGroupIndex()) {
            $QBlocks->appendQuery('AND g.id = :gruopId');
            $QBlocks->bindValue(':gruopId', $groupId);
          }
          $QBlocks->appendQuery(':limit');
          $QBlocks->bindTable(':limit', $QBlocks->addLimit($page, $limit));
          $QBlocks->execute();
          $blocks = array();
          while($QBlocks->next()) {
              $block['id']                =  $QBlocks->value('id');
              $block['title']             =  $QBlocks->value('title');
              $block['code']              =  $QBlocks->value('CODE');
              $block['language']          =  $QBlocks->value('LANGUAGE');
              $block['template']          =  $QBlocks->value('template');
              $block['css']               =  $QBlocks->value('css');
              $block['js']                =  $QBlocks->value('js');
              $block['trash']             =  iJHrefLink::linkToLocalPage('admin_blocks')    . '?delID='   . $block['id'] . '&' . iJGetAllGetParams('delID');
              $block['language_editor']   =  iJHrefLink::linkToLocalPage('language_editor') . '?blockID=' . $block['id'];
              $blocks[] =  $block;
              
          }
         
          return array($blocks, $QBlocks);
          
        }
        
        public function getBlocks() {
          $iJDataBase =  iJFactory::singleton('iJDataBase');
          $QBlocks = $iJDataBase->query('SELECT B.id, 
                                               def.value as title,
                                               B.CODE, 
                                               B.template, 
                                               B.LANGUAGE,
                                               B.css, 
                                               B.js 
                                        FROM :table_blocks AS B
                                             :lang_join ORDER BY title');
          $QBlocks->bindTable(':table_blocks', TABLE_BLOCKS);
          $QBlocks->bindLaguageDefinitions(':lang_join', TABLE_BLOCKS, 'B');
          $QBlocks->execute();
          $blocks = array();
          while($QBlocks->next()) {
              $block['id']          =  $QBlocks->value('id');
              $block['title']       =  $QBlocks->value('title');
              $block['code']        =  $QBlocks->value('CODE');
              $block['language']    =  $QBlocks->value('LANGUAGE');
              $block['template']    =  $QBlocks->value('template');
              $block['css']         =  $QBlocks->value('css');
              $block['js']          =  $QBlocks->value('js');
              $blocks[] =  $block;
              
          }
         
          return $blocks;
          
        }
        
        public function createBlockClass ($className, $location, $description) {
          if(!empty($className)) {
            if(file_exists($location . $className . '.php')) {
              return $className . '.php';
            }
            $content = file_get_contents(CLASS_EXAMPLE, FILE_TEXT);
            $content = iJReplace(':class_name', $className, $content);
            $content = iJReplace(':year',        date('Y'),                 $content);
            $content = iJReplace(':description', $description,              $content);
            $file = fopen($location . $className . '.php', "w");
            fwrite($file,utf8_encode($content)); 
            fclose ($file);
            return '';
          }
        
        }
        
        public function createBlockTemplate($blockName, $location, $className) {
            if(file_exists($location . $className . '.php')) {
              return $blockName;
            }
            $content = file_get_contents(TEMPLATE_EXAMPLE, FILE_TEXT);
            $content = iJReplace(':block', $blockName, $content);
            $content = iJReplace(':year', date('Y'), $content);
            $file = fopen($location . $blockName, "w");
            fwrite($file,"\xEF\xBB\xBF". $content); 
            fclose ($file);
            return '';
            
            
        }
        
         public function createBlockLanguge($blockName, $location) {
            $content = file_get_contents(LANGUAGE_EXAMPLE, FILE_TEXT);
            $iJDataBase =  iJFactory::singleton('iJDataBase');
            $QBlocks = $iJDataBase->query('SELECT code FROM :table_languages');
            $QBlocks->bindTable(':table_languages', TABLE_LANGUAGES);
            $QBlocks->execute();
            
            while ($QBlocks->next()) {
                if(file_exists($location . $blockName . '.php')) {
                  return $blockName;
                }
                $file = fopen($location . $QBlocks->value('code') . '/' . $blockName, "w");
                fwrite($file,"\xEF\xBB\xBF". $content); 
                fclose ($file);
                
            }
            return '';
         }
    }
    
    

?>